import { defineComponent, ExtractPropTypes, onMounted, PropType } from 'vue'
import { Table, Input, Button, Form } from 'ant-design-vue'
import type {
  PaginationProps,
  TableProps as OrginTableProps
} from 'ant-design-vue'
import { FetchApi, useTableData } from '../../tools'
import useTableSelection from './useTableSelection'

export type TableProps = Partial<Omit<OrginTableProps, 'dataSource'>>

export interface SearchOption {
  type: 'text'
  key: string
  title?: string
}

export const DialogTablePropsDefine = {
  tableAttrs: {
    type: Object as PropType<TableProps>,
    required: true
  },
  fetchApi: {
    type: Function as PropType<FetchApi>,
    required: true
  },
  searchable: {
    type: Boolean,
    default: false
  },
  searchKeys: {
    type: Array as PropType<SearchOption[]>,
    default: () => [{ type: 'text', key: 'searchText' }]
  },
  autoUpdate: {
    type: Boolean,
    default: false
  }
} as const

export type DialogTableProps = Partial<
  ExtractPropTypes<typeof DialogTablePropsDefine>
>

export default defineComponent({
  name: 'DialogTable',
  props: DialogTablePropsDefine,
  emits: ['close', 'submit'],
  setup(props, { emit }) {
    const {
      dataLoading,
      tableData,
      total,
      pageParams,
      searchParams,
      updateData,
      searchData,
      resetData,
      handlePageChange
    } = useTableData(props.fetchApi)
    const { selectedKeys, selectedData, handleSelectChange, handleSelectAll } =
      useTableSelection(props)

    onMounted(() => {
      if (props.autoUpdate) {
        updateData()
      }
    })
    /* render 函数 */
    return () => {
      const { tableAttrs, searchable, searchKeys } = props
      const { pagination, rowSelection, ...otherTableAttrs } = tableAttrs
      return (
        <div class="sps-dialog-table">
          {searchable && (
            <div class="sps-dialog-table-search">
              <Form layout="inline">
                {searchKeys.map((item) => (
                  <Form.Item label={item.title}>
                    <Input v-model:value={searchParams.value[item.key]} />
                  </Form.Item>
                ))}
                <Form.Item class="toolbar">
                  <Button class="reset-btn mr-1" onClick={resetData}>
                    重置
                  </Button>
                  <Button
                    class="search-btn"
                    type="primary"
                    onClick={searchData}
                    loading={dataLoading.value}>
                    查询
                  </Button>
                </Form.Item>
              </Form>
            </div>
          )}
          {
            //@ts-ignore
            <Table
              loading={dataLoading.value}
              {...otherTableAttrs}
              dataSource={tableData.value}
              pagination={{
                ...((pagination as PaginationProps) || {}),
                current: pageParams.page,
                pageSize: pageParams.pageSize,
                total: total.value,
                onChange: handlePageChange
              }}
              rowSelection={{
                ...(rowSelection || {}),
                selectedRowKeys: selectedKeys.value,
                onSelect: handleSelectChange,
                onSelectAll: handleSelectAll
              }}
            />
          }
          <div class="sps-dialog-table-footer">
            <Button onClick={() => emit('close')}>关闭</Button>
            <Button
              class="ml-2"
              type="primary"
              onClick={() =>
                emit('submit', {
                  value: selectedKeys.value,
                  rows: selectedData.value
                })
              }>
              确定
            </Button>
          </div>
        </div>
      )
    }
  }
})
